import axios from 'axios'
import { getToken, removeToken } from './cookie';
import router from '@/router';

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 基本路径 127.0.0.1:19090/friend
const service = axios.create({
  baseURL: '/dev-api',
  timeout: 5000 // request timeout
});

service.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    const token = getToken();
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
  },
  (error) => {
    // Do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
)

service.interceptors.response.use(
  (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code;
    const msg = res.data.msg;
    if (code === 3001) { // 用户未登录
      ElMessage.error(msg);
      removeToken();
      router.push('/oj-c/login');
    } else if (code !== 1000) {
      ElMessage.error(msg);
      return Promise.reject(new Error(msg));
    } else {
      return Promise.resolve(res.data);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
)

export default service;
